class UseFor {
	static times = new Map; //times Map
	constructor(arg) {

	}
	/**
	 * 计时函数
	 * @param {*} label 
	 * 使用方式：
	 * 
	  timeCount('label');
	  
	  //codes...
	  
	  console.log(timeCount('label'));
	 */
	timeCount(label) {
		label += '_star';
		const starTime = UseFor.times.get(label); //获取label起始值
		if (starTime) {
			UseFor.times.delete(label);
			return Date.now() - starTime; //获取时间差
		}
		UseFor.times.set(label, Date.now());
		return 'set success!'
	}
}

const ztimer = new UseFor();



let arr = [],
	resultArr = {};

// 初始数据
for (let i = 0; i < 100000000; i++) {
	arr.push(i);
}

console.time("总时间花费");
// 循环性能测试
for (let i = 0; i < 20; i++) {

	ztimer.timeCount('for')
	for (let i = 0; i < arr.length; i++) {
		let item = arr[i];
		item += 1;
	}
	addTime('forTime', ztimer.timeCount('for'));

	ztimer.timeCount('for2');
	let i = 0,
		length = arr.length;
	for (i; i < length; i++) {
		let item = arr[i];
		item += 1;
	}
	addTime('for2Time', ztimer.timeCount('for2'));

	ztimer.timeCount('foreach');
	arr.forEach(item => {
		item += 1;
	})
	addTime('foreachTime', ztimer.timeCount('foreach'));

	ztimer.timeCount('map');
	arr.map(item => {
		item += 1;
	})
	addTime('mapTime', ztimer.timeCount('map'));
}

for (let key in resultArr) {
	const item = resultArr[key]
	const average = (args) => args.reduce((a, b) => parseInt(a) + parseInt(b)) / args.length;
	item.averageVal = average(item.timeList) + 'ms';
	// console.log(item.timeList);
	// console.log(average([1,2,3,4]));
}

console.log(resultArr);

// 添加数据
function addTime(label, time) {
	if (!resultArr[label]) {
		resultArr[label] = {
			timeList: []
		};
	}
	resultArr[label].timeList.push(time + 'ms');
}



console.timeEnd('总时间花费');
